UMI3源码解析系列之运行时插件机制

您所在的位置:网站首页 react 运行时 UMI3源码解析系列之运行时插件机制

UMI3源码解析系列之运行时插件机制

2023-11-03 23:59| 来源: 网络整理| 查看: 265

前言

前面几篇文章,我们分析了umijs核心Service类的初始化流程、插件化的核心流程以及构建阶段dev命令的执行流程。那我们今天继续分析项目在运行时阶段又会做哪些事呢?

在开始今天的文章之前,大家不妨想几个问题:

自动生成的入口文件和我们平时自己写的入口文件有什么不一样? 项目中使用的插件(例如:plugin-model、plugin-request等插件)又是如何注册到项目中的? 在运行时阶段,如何动态修改路由或者如何重写render方法? umijs生成的临时文件通过其他构建工具(不限于webpack、rollup、esbuild)可以跑起来吗? 入口文件

在前面我们提到了在解析preset-built-in预设阶段会批量导入generate files相关的plugin,同时在这些plugin中注册onGenerateFiles钩子,然后在webpack编译前触发,生成临时文件。

接下来,我们从入口文件出发,看下通过执行umi dev命令生成的入口文件内容:

// path: src/.umi/umi.ts // @ts-nocheck import './core/polyfill'; import '@@/core/devScripts'; import { plugin } from './core/plugin'; import './core/pluginRegister'; import { createHistory } from './core/history'; import { ApplyPluginsType } from '~/umi-test/node_modules/@umijs/runtime'; import { renderClient } from '~/umi-test/node_modules/@umijs/renderer-react'; import { getRoutes } from './core/routes'; const getClientRender = (args: { hot?: boolean; routes?: any[] } = {}) => plugin.applyPlugins({ key: 'render', type: ApplyPluginsType.compose, initialValue: () => { const opts = plugin.applyPlugins({ key: 'modifyClientRenderOpts', type: ApplyPluginsType.modify, initialValue: { routes: args.routes || getRoutes(), plugin, history: createHistory(args.hot), isServer: process.env.__IS_SERVER, rootElement: 'root', defaultTitle: ``, }, }); return renderClient(opts); }, args, }); const clientRender = getClientRender(); export default clientRender(); window.g_umi = { version: '3.5.14', }; // hot module replacement ...

首先可以看到文件的顶部导入了polyfill文件,也就是我们平时自己开发项目导入的babel相关的polyfill文件。

当然在umi-next版本已经在尝试用swc代替babel,感兴趣的小伙伴可以自行查阅umi-next的相关issues。

// path: src/.umi/umi.ts // @ts-nocheck import 'core-js'; import 'regenerator-runtime/runtime'; export {};

接下来我们继续往下分析,通过执行getClientRender函数,返回clientRender。在getClientRender函数内部我们看到了熟悉的面孔--plugin,运行时阶段同样通过插件化返回渲染需要的render方法。

值得注意的是这里的Plugin是有别于前面提到的PluginAPI,PluginAPI是在作用于编译阶段,而Plugin是作用于运行时的插件。

接下来,我们看下运行时插件是怎么实现的。

运行时插件

阅读源码最好的出入点就是从它的测试用例出发。测试用例是题干,源码就是答案。

------加夫列尔·加西亚·马尔波斯

接下来我们从不同方向出发,更好的了解运行时插件机制的原理及实现。

从Plugin的测试用例出发

接下来,我们看下几个plugin的测试用例:

实例化时设置可允许注册的key,同时在register时会校验key是否允许 test('invalid key', () => { const p = new Plugin({ validKeys: [], }); expect(() => { p.register({ apply: { foo: 1 }, path: '/foo.js', }); }).toThrow(/invalid key foo from plugin \/foo.js/); }); 通过getHooks方法可获取指定key注册的hook test('getHooks', () => { const p = new Plugin({ validKeys: ['foo'], }); p.register({ apply: { foo: 1 }, path: '/foo1.js', }); p.register({ apply: { foo: 2 }, path: '/foo2.js', }); expect(p.getHooks('foo')).toEqual([1, 2]); }); 通过applyPlugins方法可执行指定key注册的hook,同时还支持以下三种操作: 支持依次把上一个hook的返回值作为入参传递给下一个hook 支持args当前hook的其他参数 支持默认值initialValue // path: ~/umi/packages/runtime/src/Plugin/Plugin.test.ts test('applyPlugins modify', () => { const p = new Plugin({ validKeys: ['foo'], }); p.register({ apply: { foo(memo: object) { return { ...memo, a: 1 }; }, }, path: '/foo1.js', }); p.register({ apply: { foo(memo: object, args: { step: number }) { return { ...memo, b: 1 + ((args && args.step) || 0) }; }, }, path: '/foo2.js', }); p.register({ apply: { foo: { a: 2, c: 1, }, }, path: '/foo3.js', }); // 1. 把上一个hook的返回值作为入参传递给下一个hook expect( p.applyPlugins({ key: 'foo', type: ApplyPluginsType.modify, }), ).toEqual({ a: 2, b: 1, c: 1, }); // 2. 支持args当前hook的其他参数 expect( p.applyPlugins({ key: 'foo', type: ApplyPluginsType.modify, args: { step: 5 }, }), ).toEqual({ a: 2, b: 6, c: 1, }); // 3. 支持默认值initialValue expect( p.applyPlugins({ key: 'foo', type: ApplyPluginsType.modify, initialValue: { d: 4 }, }), ).toEqual({ a: 2, b: 1, c: 1, d: 4, }); });

通过分析Plugin常见的测试用例,我们大致知道了Plugin的使用方法,那么接下来我们从源码出发,更加进一步的了解Plugin的工作流程。

从Plugin源码出发 // path: ~/umi/packages/runtime/src/Plugin/Plugin.ts export default class Plugin { validKeys: string[]; hooks: { [key: string]: any; } = {}; constructor(opts?: IOpts) { this.validKeys = opts?.validKeys || []; } // 注册插件 register(plugin: IPlugin) { assert(!!plugin.apply, `register failed, plugin.apply must supplied`); assert(!!plugin.path, `register failed, plugin.path must supplied`); Object.keys(plugin.apply).forEach((key) => { assert( this.validKeys.indexOf(key) > -1, `register failed, invalid key ${key} from plugin ${plugin.path}.`, ); if (!this.hooks[key]) this.hooks[key] = []; this.hooks[key] = this.hooks[key].concat(plugin.apply[key]); }); } // 获取 hook getHooks(keyWithDot: string) { const [key, ...memberKeys] = keyWithDot.split('.'); let hooks = this.hooks[key] || []; if (memberKeys.length) { hooks = hooks .map((hook: any) => { try { let ret = hook; for (const memberKey of memberKeys) { ret = ret[memberKey]; } return ret; } catch (e) { return null; } }) .filter(Boolean); } return hooks; } // 执行 hook applyPlugins({ key, type, initialValue, args, async, }) { const hooks = this.getHooks(key) || []; switch (type) { case ApplyPluginsType.modify: if (async) { return hooks.reduce( async (memo: any, hook: Function | Promise | object) => { if (isPromiseLike(memo)) { memo = await memo; } if (typeof hook === 'function') { const ret = hook(memo, args); if (isPromiseLike(ret)) { return await ret; } else { return ret; } } else { if (isPromiseLike(hook)) { hook = await hook; } return { ...memo, ...hook }; } }, isPromiseLike(initialValue) ? initialValue : Promise.resolve(initialValue), ); } else { return hooks.reduce((memo: any, hook: Function | object) => { if (typeof hook === 'function') { return hook(memo, args); } else { // TODO: deepmerge? return { ...memo, ...hook }; } }, initialValue); } case ApplyPluginsType.event: return hooks.forEach((hook: Function) => { hook(args); }); case ApplyPluginsType.compose: return () => { return _compose({ fns: hooks.concat(initialValue), args, })(); }; } } }

首先从Plugin初始化阶段我们可以看到,Plugin的hook是不同于构建时插件的hook,Plugin的hook在初始化阶段就定义好了允许注册hook的key,同时后续也不允许修改。在register阶段注册插件时会通过validKeys校验是否允许注册当前插件。

接下来是通过getHooks获取指定key对应的hook,在测试用例阶段我们只分析了key='foo'简单格式的用例,而在正式使用过程中还支持key='a.b.c'格式的注册方式。

Plugin执行插件同样是调用applyPlugins方法,并且支持modify、event和compose三种类型的hook。相较于构建时的插件执行流程还是比较简单的。

分析完Plugin源码,那我们再看下umijs的临时文件又是如何使用Plugin进行注册和执行hook的。

从临时文件plugin.ts出发

我们回忆下入口文件umi.ts内容:

// path: src/.umi/umi.ts // @ts-nocheck ... import { plugin } from './core/plugin'; import './core/pluginRegister'; ... const getClientRender = (args) => plugin.applyPlugins({ key: 'render', type: ApplyPluginsType.compose, initialValue: () => {}, args, }); ... // path: src/.umi/core/plugin.ts // @ts-nocheck import { Plugin } from '~/umi-test/node_modules/@umijs/runtime'; const plugin = new Plugin({ validKeys: ['modifyClientRenderOpts','patchRoutes','rootContainer','render','onRouteChange','__mfsu','getInitialState','initialStateConfig','request',], }); export { plugin }; // path: src/.umi/core/pluginRegister.ts // @ts-nocheck import { plugin } from './plugin'; import * as Plugin_0 from '../plugin-initial-state/runtime'; import * as Plugin_1 from '../plugin-model/runtime'; plugin.register({ apply: Plugin_0, path: '../plugin-initial-state/runtime', }); plugin.register({ apply: Plugin_1, path: '../plugin-model/runtime', });

分析上面代码,首先会从./core/plugin文件导入实例化好的plugin,同时在./core/pluginRegister中注册plugin,然后在入口执行key=render的hook获取渲染所需的render方法。

接下来,我们再看下临时文件plugin.ts和pluginRegister.ts是如何生成的。

从生成文件plugin.ts的插件出发 // path: ~/umi/packages/preset-built-in/src/plugins/generateFiles/core/plugin.ts export default function (api: IApi) { api.onGenerateFiles(async (args) => { const validKeys = await api.applyPlugins({ key: 'addRuntimePluginKey', type: api.ApplyPluginsType.add, initialValue: [ 'modifyClientRenderOpts', 'patchRoutes', 'rootContainer', 'render', 'onRouteChange', '__mfsu', ], }); const plugins = await api.applyPlugins({ key: 'addRuntimePlugin', type: api.ApplyPluginsType.add, initialValue: [ getFile({ base: paths.absSrcPath!, fileNameWithoutExt: 'app', type: 'javascript', })?.path, ].filter(Boolean), }); api.writeTmpFile({ path: 'core/plugin.ts', content: Mustache.render( readFileSync(join(__dirname, 'plugin.tpl'), 'utf-8'), { validKeys, runtimePath, }, ), }); api.writeTmpFile({ path: 'core/pluginRegister.ts', content: Mustache.render( readFileSync(join(__dirname, 'pluginRegister.tpl'), 'utf-8'), { plugins: plugins.map((plugin: string, index: number) => { return { index, path: winPath(plugin), }; }), }, ), }); }); ... }

分析生成文件plugin.ts的插件,我们可以看到这个插件主要做了4件事:

调用构建时插件的addRuntimePluginKey的hook获取运行时插件所需的validKeys

注:我们开发自定义插件时,可以通过addRuntimePluginKey注册自定义的validKey

调用构建时插件的addRuntimePlugin的hook获取**运行时所需的插件

注:我们可以看到运行时插件的默认值initialValue是从src/app文件中获取的,也就是在src/app文件中注册我们所需的hook,例如:通过patchRoutes更改路由、通过onRouteChange设置标题等操作

读取plugin.tpl模版,生成临时文件plugin.ts

读取pluginRegister.tpl模版,生成临时文件pluginRegister.ts

接下来,回到入口文件.umi/umi.ts的getClientRender方法。

import { renderClient } from '~/umi-test/node_modules/@umijs/renderer-react'; const getClientRender = (args: { hot?: boolean; routes?: any[] } = {}) => plugin.applyPlugins({ key: 'render', type: ApplyPluginsType.compose, initialValue: () => { // 获取 renderClient 方法所需的参数 const opts = plugin.applyPlugins({ key: 'modifyClientRenderOpts', type: ApplyPluginsType.modify, initialValue: { routes: args.routes || getRoutes(), plugin, history: createHistory(args.hot), isServer: process.env.__IS_SERVER, rootElement: 'root', defaultTitle: ``, }, }); return renderClient(opts); }, args, }); const clientRender = getClientRender(); export default clientRender();

从上面代码,可以看出执行clientRender方法返回的结果就是执行renderClient方法的返回值。那么接下来,我们看下renderClient方法到底做了哪些事情。

renderClient

从上面可以看到renderClient方法是从@umijs/renderer-react包中导出的:

// path: ~/umi/packages/renderer-react/src/renderClient/renderClient.tsx import { hydrate, render } from 'react-dom'; export default function renderClient(opts: IOpts) { const rootContainer = opts.plugin.applyPlugins({ type: ApplyPluginsType.modify, key: 'rootContainer', initialValue: ( ), args: { history: opts.history, routes: opts.routes, plugin: opts.plugin, }, }); if (opts.rootElement) { const rootElement = typeof opts.rootElement === 'string' ? document.getElementById(opts.rootElement) : opts.rootElement; const callback = opts.callback || (() => {}); // flag showing SSR successed if (window.g_useSSR) { ... } else { render(rootContainer, rootElement, callback); } } else { return rootContainer; } }

分析renderClient方法主要做了2件事:

触发rootContainer运行时阶段的hook,获取rootContainer组件 获取rootElementDOM元素 rootContainer作为根组件,rootElement作为根元素,执行render方法,挂载组件,此时的render方法也就是react-dom导出的render方法

接下来,我们再看下rootContainer组件的initialValue:

import { ApplyPluginsType, Plugin, Router } from '@umijs/runtime'; function RouterComponent(props: IRouterComponentProps) { const { history, ...renderRoutesProps } = props; useEffect(() => { function routeChangeHandler(location: any, action?: string) { ... // 触发 onRouteChange 对应的 hook props.plugin.applyPlugins({ key: 'onRouteChange', type: ApplyPluginsType.event, args: { routes: props.routes, matchedRoutes, location, action, }, }); } routeChangeHandler(history.location, 'POP'); return history.listen(routeChangeHandler); }, [history]); return {renderRoutes(renderRoutesProps)}; }

这里RouterComponent返回的Router也就是react-router-dom包中导出的Router组件,同时在RouterComponent组件内部监听history,在history发生变化时触发运行时阶段的onRouteChange对应的hook,此时也就可以触发我们自己在业务代码中订阅的onRouteChange的回调了,例如:监听路由改变时,发送埋点或者改变document.title。

到这里,umijs项目也就可以跑起来了。那么执行umi dev命令生成的临时文件,同样是通过umijs内部的webpack构建工具以及umijs内部自己实现的server让项目跑起来的,也就是说如果我们仅仅是让umijs帮我们生成临时文件,而项目的构建通过第三方构建工具是否也是可以呢?

接下来,我们通过esbuild如何让项目跑起来呢?

通过esbuild构建临时文件

An extremely fast JavaScript bundler.

简单介绍下esbuild:它是一个极速的模块打包工具,有着相较于webpack、rollup等构建工具高到离谱的性能优势。至于esbuild构建速度为何如此之快,首先从语言特性(esbuild底层是使用Go语言开发的)就赢了一半,尤其在资源打包这种CPU密集场景下,感兴趣的小伙伴可以自行查询亦或持续关注我们的公众号。

除了构建功能,esbuild还提供了服务。话不多说,上代码:

const esbuild = require('esbuild'); const http = require('http'); const path = require('path') const { lessLoader } = require('esbuild-plugin-less') esbuild.serve({ // 服务根路径 servedir: path.resolve(__dirname, 'www'), }, { format: 'iife', logLevel: 'error', outdir: 'www/', platform: "browser", bundle: true, define: { // HOOK:umi 内部会用到 'process.env.__IS_SERVER': JSON.stringify('null') }, plugins: [lessLoader({ javascriptEnabled: true })], external: ['esbuild'], // 入口文件 entryPoints: [path.resolve(__dirname, 'src/.umi/umi.ts')] }).then(result => { console.log('service: ', `http://127.0.0.1:${result.port}`); });

我们通过esbuild提供的serveAPI在本地开启web服务器来为我们通过esbuild构建生成的代码提供服务。简单介绍下esbuild的使用方法:

定义服务根路径servedir 定义入口文件entryPoints以及出口路径outdir 同时还需要设置platform和bundle

最后一点就是esbuild默认是不支持less文件,需要设置额外的插件(esbuild-plugin-less)进行解析less文件。

附:通过esbuild构建umijs临时文件的demo。

总结

聊到插件化架构,我们更多想到的是构建阶段的插件机制(不限于webpack、babel),而umijs提供的运行时阶段的插件机制就比较少见了。相较于构建时插件,运行时插件就比较简单,运行时插件更多做的事情偏向于渲染相关。而这观点又该如何更加合理的应用到业务层逻辑,也是值得探索的。

同时通过对esbuild构建umijs生成的临时文件的探索,也是可以看到umijs在插件设计以及各个环节的解耦能力还是很值得学习的。以及对esbuild工具的使用,也可以看出在前端领域被原生JavaScript所局限的痛点问题,最终也会被更高效的语言所优化解决,当然这些工具投入生产使用也是值得商榷的,更多的是如何去学习和了解这些优秀的设计思路。

读到这里,相信各位小伙伴对文章最初提的几个问题也有了自己的答案,当然每个人的答案可能是不尽相同。有什么疑问,欢迎各位小伙伴一起交流学习。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3